package com.flyee.viewer.pack.helper
{
	import com.flyee.controller.CharacterCartoonController;
	import com.flyee.controller.SkillPanelController;
	import com.flyee.events.SelectionEvent;
	import com.flyee.service.pool.ObjectCollection;
	import com.flyee.utils.EventManager;
	import com.flyee.utils.MyLog;
	
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	
	import mx.controls.Alert;
	import mx.core.Application;
	import mx.core.UIComponent;

	public class ItemsContainer extends UIComponent
	{
		/**
		 * 行列
		 */
		private var row:int=0;
		private var column:int=0;
		/**
		 * 格子总数
		 */
		private var totalCell:int=0;
		/**
		 * 保存所有格子实例的数组
		 */
		private var cellList:Array=null;
		/**
		 * 面板的宽和高
		 */
		private var panelW:int=0;
		private var panelH:int=0;
		private const WIDTH_CELL:int=40;
		private const HEIGHT_CELL:int=40;
		private const V_GAP:int=5;
		private const H_GAP:int=5;
		private var propList:Array=null;
		private var isDrag:Boolean=false;
		/**
		 * 组合购买道具时拖动的目标道具实例引用
		 */
		private var selectedProp:ItemViewModel=null;
		private var oldTime:Number=0;
		/**
		 * 该面板容器的编号
		 */
		private var panelIndex:int=0;
		/**
		 * 组合拆分道具时保存的源道具实例引用
		 */
		private var rootProp:ItemViewModel=null;
		/**
		 * 判断shift是否按下
		 */
		private var isShiftKey:Boolean=false;
		/**
		 * 记录拆分到哪个格子
		 */
		private var splitIndex:int=-1;
		/**
		 * 包裹逻辑的处理器
		 */
		private var helper:ItemHelper=null;

		/**
		 * 放物品的面板容器，单个包裹容器，包含多个cell组件
		 * @param row
		 * @param column
		 *
		 */
		public function ItemsContainer(row:int=5, column:int=7)
		{
			super();
			this.row=row;
			this.column=column;
			init();
		}

		/**
		 *  初始化方法
		 *
		 */
		private function init():void
		{
			this.totalCell=row * column;
			panelW=WIDTH_CELL * column + H_GAP * (column - 1);
			panelH=HEIGHT_CELL * row + V_GAP * (row - 1);
			propList=new Array(totalCell);
			createCellPanel();
			helper=new ItemHelper(this);

			if (PackageHelper.AVERAGE_COUNT != totalCell)
			{
				PackageHelper.AVERAGE_COUNT=totalCell;
			}
			oldTime=new Date().getTime();
			EventManager.registListener(SelectionEvent.DRAG_PROP, addListenerHandler);
		}

		/**
		 * 初始化单元格容器面板
		 *
		 */
		private function createCellPanel():void
		{
			var leng:int=row * column;
			cellList=new Array(leng);

			for(var i:int=0; i < leng; i++)
			{
				var cell:CellGridBox=new CellGridBox();
				cell.setCellIndex(i);
				cell.setPosition(this.calculatePostion(i));
				cellList[i]=cell;
				this.addChild(cell);
			}
		}

		/**
		 * 按从左到右，从上到下的顺序得到第一个空Cell的位置索引
		 * @return
		 *
		 */
		private function getEmptyIndex():int
		{
			var index:int=-1;
			var i:int=0;

			while(i < this.totalCell)
			{

				if (!CellGridBox(cellList[i]).isFilled())
				{
					index=i;
					break;
				}
				i++;
			}
			return index;
		}

		private function isEmptyCell(index:int):Boolean
		{
			var cell:CellGridBox=cellList[index]as CellGridBox;

			if (!cell.isFilled())
			{
				return true;
			}
			return false;
		}

		/**
		 * 根据行列数计算Cell的位置坐标
		 * @param i
		 * @return
		 *
		 */
		private function calculatePostion(i:int):Point
		{
			var index:int=i;
			var pos:Point=new Point();
			var max:int=column > row ? column : row;
			var hor:int=Math.floor(index % max);
			var ver:int=Math.floor(index / max);
			pos.x=hor * (WIDTH_CELL + H_GAP) + 1 + H_GAP;
			pos.y=ver * (HEIGHT_CELL + V_GAP) + 1 + V_GAP;
			return pos;
		}

		private function addListenerHandler(event:SelectionEvent):void
		{
			var prop:ItemViewModel=event.entity as ItemViewModel;
			prop.addEventListener(SelectionEvent.DRAG_PROP, draggingHandler);
		}

		/**
		 * 拖动道具过程处理事件
		 * @param e
		 *
		 */
		private function draggingHandler(event:SelectionEvent):void
		{
			var prop:ItemViewModel=event.entity as ItemViewModel;
			isDrag=true;
			for(var i:int=0; i < this.totalCell; i++)
			{
				var cell:CellGridBox=cellList[i]as CellGridBox;
				if (cell.hitTestPoint(Application.application.stage.mouseX, Application.application.stage.mouseY, true))
				{
					cell.hitEffect = true;
				}else{
					cell.hitEffect = false;
				}
			}
			//isShiftKey=KeyboardEventManager.getInstance().isKeyDown(Keyboard.SHIFT);
			this.dispatchEvent(new SelectionEvent(SelectionEvent.SELECTED, prop.dataModel.id, prop.dataModel.name, prop));
			this.removeEventListener(SelectionEvent.DRAG_PROP, draggingHandler);
		}

		/**
		 * 双击道具换装的事件
		 * @param e
		 *
		 */
		private function clickHandler(e:MouseEvent):void
		{
			var prop:ItemViewModel=e.target as ItemViewModel;
			//var time:Number=new Date().getTime();
			//var div:Number=0;
			//div=time - oldTime;

			//if (div < 600)
			//{
				MyLog.debug("double click for using one prop...");

				//该道具是否可以使用
				if (prop.dataModel.instanceStatus == ItemDataModel.STATUS_NORMAL)
				{
					MyLog.debug("this prop could be used...");
					var restrict:int=prop.dataModel.restrict;
					var grade:int=0;

					if (grade < restrict)
					{
						Alert.show("等级不够，无法使用！请先升级！", "提示");
					}
					else
					{
						MyLog.debug("the condition is suitable for grade ..." + prop.name);
						var type:int=prop.dataModel.itemGenre;

						/* if (type == ItemDataModel.APPEARANCE_TYPE)
						{
							//processor.excuteFunction(prop);
						}
						else
						{ */
							//该道具是否正在使用
							var skillController:SkillPanelController = 
									ObjectCollection.beansContext.getObject("skillPanelController") as SkillPanelController;
							if(skillController == null) return;
							if(prop.dataModel.itemType == 1000){
								skillController.charactorService.sendSkill(4);
								var cell:CellGridBox = cellList[prop.dataModel.currentPosistion];
								var itemData:ItemDataModel = ObjectCollection.skillPanelViewer.drugItems.getItemAt(0) as ItemDataModel;
								cell.stackCount = itemData.currentCapability;
								prop.dataModel.capability = itemData.currentCapability;
								if(prop.dataModel.currentCapability < 1){
									removeProp(prop);
								}
								ObjectCollection.skillPanelViewer.drugItems.refresh();
							}else if(prop.dataModel.itemType == 2000){
								skillController.changeEquip(prop.dataModel.id);
								if(ObjectCollection.equipViewer){
									var item:ItemViewModel = ItemHelper.cloneProp(prop.dataModel,false,prop.icon);
									item.isDrag = false;
									ObjectCollection.equipViewer.addEquip(item);
								}
							}
							/* if (!prop.isUsing())
							{
								//将道具设为使用
								prop.setUsing(true);
								//helper.itemUsing(prop);
								var cartoonController:CharacterCartoonController = 
									ObjectCollection.beansContext.getObject("characterCartoonController") as CharacterCartoonController;
								cartoonController.loadCharacterPlate(ObjectCollection.master,ObjectCollection.masterViewer,prop.dataModel.id);
							} 
						}*/
					}
				}
			//}
			//oldTime=time;
		}

		/**
		 * 停止道具拖动处理，并把道具加到面板中，包括同一个包裹中道具的合并，拆分操作
		 * @param absProp
		 *
		 */
		private function stopMovingItem(absProp:ItemViewModel):Boolean
		{
			var prop:ItemViewModel=absProp;

			if (prop.dataModel.packPanelIndex != this.panelIndex)
			{
				//从别的包裹拖过来的
				var emptyPos:int=getEmptyIndex();

				if (emptyPos > -1)
				{
					//当前包裹还有空格子
					var emptyCell:CellGridBox=cellList[emptyPos]as CellGridBox;
					prop.dataModel.position=emptyCell.cellIndex;
					prop.dataModel.packPanelIndex=this.panelIndex;
					this.propList[emptyPos]=prop;
					emptyCell.addProp(prop);
					return true;
				}
				else
				{
					return false;
				}
			}
			else
			{
				//同一个包裹中进行拖动
				var oldCell:CellGridBox=null;

				for(var j:int=0; j < this.totalCell; j++)
				{

					if (prop.dataModel.currentPosistion == CellGridBox(cellList[j]).cellIndex)
					{
						oldCell=cellList[j]as CellGridBox;
						break;
					}
				}

				/* if (oldCell)
				   {
				   oldCell.removeData();
				 } */

				for(var i:int=0; i < this.totalCell; i++)
				{
					var cell:CellGridBox=cellList[i]as CellGridBox;

					if (cell.hitTestPoint(Application.application.stage.mouseX, Application.application.stage.mouseY, true))
					{
						//oldCell.hitEffect = false;
						cell.hitEffect = false;
						if (oldCell && oldCell.cellIndex == cell.cellIndex)
						{
							//oldCell.addProp(prop);
						}
						else
						{

							//所放的格子已经被占了
							if (cell.isFilled())
							{
								/* if (oldCell)
								   {
								   oldCell.removeData();
								 } */
								var temp:ItemViewModel=cell.absProp;

								//判断两个道具是否可以合并
								if (isMerage(temp, prop))
								{
									rootProp=temp;
									selectedProp=prop;
									MyLog.debug("could merge these props..." + rootProp.name + "::" + selectedProp.name);
									var sum:int=prop.dataModel.currentCapability + temp.dataModel.currentCapability;
									//合并后的道具数量
									var count:int=0;

									if (sum > prop.dataModel.capabilityMax)
									{
										count=sum - prop.dataModel.capabilityMax;
									}
									else
									{
										count=sum;
									}
									//将要合并的位置
									var aindex:int=temp.dataModel.currentPosistion + this.panelIndex * PackageHelper.AVERAGE_COUNT;
									var oldPos:int=prop.dataModel.currentPosistion;
									var newPos:int=temp.dataModel.currentPosistion;
									helper.mergeItems(oldPos, newPos, count);
								}
								else
								{
									//不能组合则放回到原来的格子中去
									oldCell.addProp(prop);
								}
							}
							else
							{
								MyLog.debug("stop drag then split prop..." + isShiftKey + "::" + prop.dataModel.currentCapability);

								//如果所拖动的道具在放下时shift是一直是被按下的，且该道具数量大于一,则可以拆分
								if (isShiftKey && prop.dataModel.currentCapability > 1)
								{
									/* isShiftKey=false;
									rootProp=prop;
									this.splitIndex=cell.cellIndex;
									MyLog.debug("could split these props..." + rootProp.name);
									var numStepper:NumberStepperBox=new NumberStepperBox();
									numStepper.tipMessage="请输入拆分的数量：";
									numStepper.maxCount=prop.dataModel.currentCapability;
									numStepper.addEventListener(SelectionEvent.SPLIT_PROP, numInputSureEvent, false, 0, true);
									numStepper.addEventListener(CloseEvent.CLOSE, numInputCloseEvent, false, 0, true);
									numStepper.x=(this.panelW - numStepper.width) / 2;
									numStepper.y=(this.panelH - numStepper.height) / 2;
									this.addChild(numStepper); */
								}
								else
								{
									//否则直接放到空的格子里
									var oldpos:int=prop.dataModel.currentPosistion;
									var newpos:int=cell.cellIndex;
									var amount:int=prop.dataModel.currentCapability;
									//helper.adaptItemPosition(oldpos, newpos, amount);
									var oldPosItem:ItemViewModel=getItemByPosition(prop.dataModel.id, oldpos);
									var newPosCell:CellGridBox=getCellByPosition(newpos);
									var oldPosCell:CellGridBox=getCellByPosition(oldpos);
									if (oldPosItem && newPosCell && oldPosCell)
									{
										oldPosCell.removeData();
										this.propList[oldpos]=null;
										oldPosItem.dataModel.position=newPosCell.cellIndex;
										oldPosItem.dataModel.packPanelIndex=this.panelIndex;
										this.propList[newPosCell.cellIndex]=oldPosItem;
										newPosCell.addProp(oldPosItem);
									}
									else
									{
										this.dispatchEvent(new Event("refreshPackage"));
									}
								}
							}
							break;
						}
					}
				}
			}
			isShiftKey=false;
			return false;
		}

		/* private function numInputCloseEvent(event:Event):void
		{
			var target:NumberStepperBox=event.currentTarget as NumberStepperBox;
			target.removeEventListener(SelectionEvent.SPLIT_PROP, numInputSureEvent);
			target.removeEventListener(CloseEvent.CLOSE, numInputCloseEvent);

			target.clearAll();
			this.removeChild(target);
			target=null;
		} */

		/**
		 * 拆分多个道具时，数字输入后的确定处理
		 * @param e
		 *
		 */
		/* private function numInputSureEvent(event:SelectionEvent):void
		{
			//子组道具的个数
			var num:int=parseInt(event.key);
			var target:NumberStepperBox=event.currentTarget as NumberStepperBox;
			target.removeEventListener(SelectionEvent.SPLIT_PROP, numInputSureEvent);
			target.removeEventListener(CloseEvent.CLOSE, numInputCloseEvent);
			target.clearAll();
			this.removeChild(target);
			target=null;

			MyLog.debug("stop drag then split prop..." + num);
			if (num > 0)
			{
				if (splitIndex > -1)
				{
					var count:int=rootProp.dataModel.currentCapability;
					//拆分以后的将要保存子组道具的格子
					var newCell:CellGridBox=cellList[splitIndex]as CellGridBox;
					//拆分后，将要保存子组道具在服务器上的位置						
					var newPosition:int=newCell.cellIndex + this.panelIndex * PackageHelper.AVERAGE_COUNT;
					//被拆分的道具位置
					var oldPosition:int=rootProp.dataModel.currentPosistion;
					if (num < count)
					{
						//父组道具的个数
						var div:int=count - num;
						helper.splitItems(oldPosition, newPosition, num);
					}
					else
					{
						helper.adaptItemPosition(oldPosition, newPosition, count);
					}
				}
			}
			else
			{

			}
			splitIndex=-1;
			rootProp=null;
		} */

		/**
		 * 买道具的处理
		 * @param prop
		 * @param gold
		 * @param blue
		 *
		 */
		/* private function startForPurchasing(item:ItemViewModel, gold:int, blue:int):void
		{
			var cityCoin:int=item.dataModel.priceCityCoin;
			var goldCoin:int = item.dataModel.priceGoldCoin;
			MyLog.debug("confirm could buy one prop to package..." + gold);

			if (gold < goldCoin || blue < cityCoin)
			{
				//包裹里的钱少于所买道具的钱,不能购买该道具
				Alert.show("余额不足，是否充值？", "提示");
			}
			else
			{
				//可以购买道具
				var temp:ValidateBuyPanel=UIManager.getInstance().addToDesktopByName(ValidateBuyPanel.NAME)as ValidateBuyPanel;
				temp.itemData=item.dataModel;
				temp.addEventListener(ValidationEvent.VALIDATED, validateBuyItemEvent);
				temp.addEventListener(ValidationEvent.INVALIDATED, validateBuyItemEvent);
			}
		}
 */
		/**
		 * 确认购买，购买之前保存现在包裹中的数据
		 * @param e
		 *
		 */
		/* private function validateBuyItemEvent(event:ValidationEvent):void
		{
			var target:ValidateBuyPanel=event.currentTarget as ValidateBuyPanel;
			target.removeEventListener(ValidationEvent.VALIDATED, validateBuyItemEvent);
			target.removeEventListener(ValidationEvent.INVALIDATED, validateBuyItemEvent);
			//同意购买
			if (event.type == ValidationEvent.VALIDATED)
			{
				var count:int=parseInt(event.message);
				selectedProp.dataModel.capability=count;
				helper.buyItem(selectedProp.dataModel.id, count, selectedProp.dataModel.currentPosistion);
			}
			else if (event.type == ValidationEvent.INVALIDATED)
			{
				//取消购买
				UIManager.getInstance().removedFromDesktopByName(ValidateBuyPanel.NAME);
			}
		} */


		/**
		 * 判断道具2是否可以合并到道具1中
		 * @param prop1
		 * @param prop2
		 * @return
		 *
		 */
		private function isMerage(prop1:ItemViewModel, prop2:ItemViewModel):Boolean
		{

			if (prop1 && prop2)
			{
				var id1:String=prop1.dataModel.id;
				var id2:String=prop2.dataModel.id;
				var max:int=prop1.dataModel.capabilityMax;

				//是同类道具
				if (id1 == id2)
				{

					//允许堆叠
					if (max > 0)
					{

						//状态一致
						if (prop1.dataModel.instanceStatus == ItemDataModel.STATUS_NORMAL && prop2.dataModel.instanceStatus == ItemDataModel.STATUS_NORMAL)
						{
							var num1:int=prop1.dataModel.currentCapability;
							if (num1 < max)
							{
								return true;
							}
						}
					}
				}
			}
			return false;
		}

		/**
		 *  拆分道具，把parentProp中的num个放到index位置的格子中
		 * @param prop
		 * @param index
		 * @param num
		 * @return
		 *
		 */
		private function splitProps(parentProp:ItemViewModel, index:int, num:int):Boolean
		{
			//将要保存子组道具的格子
			var acell:CellGridBox=cellList[index]as CellGridBox;
			//保存父组道具的格子索引
			var bindex:int=parentProp.dataModel.currentPosistion;
			//保存父组道具的格子
			var bcell:CellGridBox=cellList[bindex]as CellGridBox;
			//在原来格子中该道具叠加的个数
			var count:int=parentProp.dataModel.currentCapability;

			if (num > 0)
			{

				//当子组道具数量大于0则说明可以拆分
				if (num < count)
				{
					//把拆分后的子组道具移动到新的格子中，父组道具则减去对应的数值
					var div:int=count - num;
					parentProp.dataModel.capability=div;
					parentProp.dataModel.position=bcell.cellIndex + this.panelIndex * PackageHelper.AVERAGE_COUNT;
					bcell.stackCount=div;
					var children:ItemViewModel=ItemHelper.cloneProp(parentProp.dataModel, false, parentProp.icon);
					children.dataModel.capability=num;
					children.dataModel.position=acell.cellIndex + this.panelIndex * PackageHelper.AVERAGE_COUNT;
					this.propList[index]=children;
					acell.addProp(children);
				}
				else
				{
					//把父组道具全部移动到新的格子中
					this.propList[parentProp.dataModel.currentPosistion]=null;
					parentProp.dataModel.packPanelIndex=panelIndex;
					parentProp.dataModel.position=acell.cellIndex + this.panelIndex * PackageHelper.AVERAGE_COUNT;
					this.propList[acell.cellIndex]=parentProp;
					bcell.removeData();
					acell.addProp(parentProp);
				}
			}
			else
			{
			}
			return false;
		}

		/**
		 * 合并两个格子里的同类道具，把prop2叠加到prop1所在的格子中
		 * @param prop1
		 * @param prop2 需要合并的道具
		 *
		 */
		private function mergeProps(prop1:ItemViewModel, prop2:ItemViewModel):Boolean
		{

			if (isMerage(prop1, prop2))
			{
				var count1:int=prop1.dataModel.currentCapability;
				var count2:int=prop2.dataModel.currentCapability;
				var sum:int=count1 + count2;
				var index1:int=prop1.dataModel.currentPosistion;
				var index2:int=prop2.dataModel.currentPosistion;
				var cell1:CellGridBox=null;
				var leng:int=cellList.length;
				var max:int=prop1.dataModel.capabilityMax;

				if (sum > max)
				{
					//合并后新的道具数量大于允许的最大堆叠数量
					var div:int=sum - max;

					if (index1 < leng && index2 < leng)
					{
						var cell2:CellGridBox=cellList[index2]as CellGridBox;
						cell1=cellList[index1]as CellGridBox;
						cell1.stackCount=max;
						prop1.dataModel.capability=max;
						prop1.dataModel.position=cell1.cellIndex + this.panelIndex * PackageHelper.AVERAGE_COUNT;
						prop2.dataModel.capability=div;
						prop2.dataModel.position=cell2.cellIndex + this.panelIndex * PackageHelper.AVERAGE_COUNT;
						cell2.addProp(prop2);
						return true;
					}
					else
					{
						this.dispatchEvent(new Event("refreshPackage"));
						MyLog.debug("something error for merging prop..." + index1 + "::" + index2);
					}
				}
				else
				{

					if (index1 < leng && index2 < leng)
					{
						cell1=cellList[index1]as CellGridBox;
						prop1.dataModel.capability=sum;
						prop1.dataModel.position=cell1.cellIndex + this.panelIndex * PackageHelper.AVERAGE_COUNT;
						cell1.stackCount=sum;
						removeProp(prop2);
						return true;
					}
					else
					{
						this.dispatchEvent(new Event("refreshPackage"));
						MyLog.debug("something error for merging prop..." + index1);
					}
				}
			}
			return false;
		}

		/**
		 * 把prop添加到pos位置的cell中
		 * @param prop
		 * @param pos
		 * @param option
		 *
		 */
		private function add(prop:ItemViewModel, pos:int, option:String=null):void
		{
			var cell:CellGridBox=cellList[pos]as CellGridBox;
			prop.dataModel.currentPosistion=cell.cellIndex;
			prop.dataModel.packPanelIndex=this.panelIndex;
			propList[pos]=prop;
			cell.addProp(prop);
			if (option)
			{
				cell.stackCount=1;
			}
			prop.doubleClickEnabled = true;
			prop.addEventListener(MouseEvent.DOUBLE_CLICK, clickHandler);
		}

		private function addNewProp(prop:ItemViewModel, index:int):Boolean
		{
			var temp:ItemViewModel=null;
			var cell:CellGridBox=null;
			var pos:int=-1;
			var count:int=prop.dataModel.currentCapability;
			var oldcount:int=prop.dataModel.capabilityMax;
			var leng:int=propList.length;

			//查找移动以后道具位置
			for(var i:int=0; i < leng; i++)
			{
				temp=propList[i]as ItemViewModel;

				if (temp && temp.dataModel.initPosition == index)
				{
					oldcount=temp.dataModel.currentCapability;

					if (count > oldcount)
					{
						pos=i;
						temp.dataModel.capability=count;
						break;
					}
				}
			}

			if (pos > -1 && pos < leng)
			{
				//找到移动以后的道具，则直接在显示的数字上加一
				cell=cellList[pos]as CellGridBox;
				cell.stackCount=count;
				return true;
			}
			else
			{
				return false;
			}
		}

		/**
		 * 合并相同道具的服务器数据处理
		 * @param data
		 *
		 */
		public function mergeItems(oldData:ItemDataModel, newData:ItemDataModel):void
		{
			var oldItem:ItemViewModel=getItemByPosition(oldData.id, oldData.currentPosistion);
			var newItem:ItemViewModel=getItemByPosition(newData.id, newData.currentPosistion);
			if (oldItem && newItem)
			{
				mergeProps(newItem, oldItem);
			}
			else
			{
				this.dispatchEvent(new Event("refreshPackage"));
			}
			rootProp=null;
			selectedProp=null;
		}

		/**
		 * 拆分同类道具的服务器数据处理
		 * @param data
		 *
		 */
		public function splitItemGroup(oldData:ItemDataModel, newData:ItemDataModel):void
		{
			var newPosition:int=newData.currentPosistion;
			var newCount:int=newData.currentCapability;
			var item:ItemViewModel=getItemByPosition(oldData.id, oldData.currentPosistion);
			if (item)
			{
				splitProps(item, newPosition, newCount);
			}
			else
			{
				this.dispatchEvent(new Event("refreshPackage"));
			}
			rootProp=null;
			splitIndex=-1;

		}

		/**
		 * 移动道具的服务器结果处理
		 * @param oldData
		 * @param newData
		 *
		 */
		public function adaptItemPosition(oldData:ItemDataModel, newData:ItemDataModel):void
		{
			var oldPosItem:ItemViewModel=getItemByPosition(oldData.id, oldData.currentPosistion);
			var newPosCell:CellGridBox=getCellByPosition(newData.currentPosistion);
			var oldPosCell:CellGridBox=getCellByPosition(oldData.currentPosistion);
			if (oldPosItem && newPosCell && oldPosCell)
			{
				oldPosCell.removeData();
				this.propList[oldData.currentPosistion]=null;
				oldPosItem.dataModel.position=newPosCell.cellIndex;
				oldPosItem.dataModel.packPanelIndex=this.panelIndex;
				this.propList[newPosCell.cellIndex]=oldPosItem;
				newPosCell.addProp(oldPosItem);
			}
			else
			{
				this.dispatchEvent(new Event("refreshPackage"));
			}
		}

		/**
		 * 拖动道具填加到碰撞到的CELL
		 * @param pro
		 * @param gold
		 * @param blue
		 *
		 */
		public function fillCell(pro:ItemViewModel, gold:int=0, blue:int=0):Boolean
		{
			var prop:ItemViewModel=pro;
			if (!prop.dataModel.isSystem)
			{
				//包裹面板内部拖动
				return stopMovingItem(prop);
			}
			else
			{

				//从其他面板拖动到该面板
				for(var i:int=0; i < this.totalCell; i++)
				{
					var cell:CellGridBox=cellList[i]as CellGridBox;

					if (cell.hitTestPoint(Application.application.stage.mouseX, Application.application.stage.mouseY, true))
					{

						if (cell.isFilled())
						{
							MyLog.debug("full!!!");
						}
						else
						{
							/* var validatePanel:UIComponent=UIManager.getInstance().getPanelByName(ValidateBuyPanel.NAME);
							if (validatePanel)
							{
								Alert.show("异常操作！", "提示");
							}
							else
							{
								selectedProp=prop;
								selectedProp.dataModel.currentPosistion=cell.cellIndex;
								selectedProp.dataModel.packPanelIndex=this.panelIndex;
								startForPurchasing(prop, gold, blue);
							} */
						}
						break;
					}
				}
				return false;
			}
		}

		/**
		 * 向面板中添加一个道具
		 * @param prop
		 * @param index
		 *
		 */
		public function addProp(prop:ItemViewModel, index:int=-1):void
		{
			var pos:int=index;
			var cell:CellGridBox=null;

			if (pos == -1)
			{
				pos=getEmptyIndex();

				if (pos == -1)
				{
					MyLog.debug("pack is full!!!");
				}
				else
				{
					add(prop, pos);
				}
			}
			else
			{
				if (!isEmptyCell(pos))
				{
					pos=getEmptyIndex();
				}
				add(prop, pos);
			}
		}

		/**
		 * 当拾取一个道具时，在包裹中更新该道具
		 * @param prop
		 * @param pos
		 * @return
		 *
		 */
		public function updateProp(prop:ItemViewModel):Boolean
		{
			var index:int=prop.dataModel.currentPosistion;
			var itemid:String=prop.dataModel.id;
			var temp:ItemViewModel=null;
			var cell:CellGridBox=null;
			var tag:Boolean=false;
			//当该道具的位置在包裹中对应位置是空Cell，则说明原来的道具已经被移动了，但还没有通知数据库
			if (isEmptyCell(index))
			{
				tag=addNewProp(prop, index);
				if (!tag)
				{
					add(prop, index, "pickup");
				}
				return true;
			}
			else
			{
				//当所更新的位置已经有道具的时候
				cell=cellList[index]as CellGridBox;
				temp=cell.absProp;
				//当两个道具满足合并条件时
				if (temp.dataModel.id == prop.dataModel.id)
				{
					//类型一致
					if (temp.dataModel.instanceStatus == ItemDataModel.STATUS_NORMAL && prop.dataModel.instanceStatus == ItemDataModel.STATUS_NORMAL)
					{
						//状态一致
						var max:int=temp.dataModel.capabilityMax;
						var count:int=temp.dataModel.currentCapability;
						if (count < max)
						{
							//不是最大叠加数，则直接加一个
							cell.stackCount=count + 1;
							temp.dataModel.capability=temp.dataModel.currentCapability + 1;
							return true;
						}
						else
						{
							//重新找个空的位置
							index=getEmptyIndex();
							if (index > 1)
							{
								add(prop, index, "pickup");
								return true;
							}
						}
					}
				}
				else
				{
					//重新找原来道具的位置
					tag=addNewProp(prop, index);
					if (!tag)
					{
						index=getEmptyIndex();
						if (index > -1)
						{
							//还有空的位置
							add(prop, index, "pickup");
							return true;
						}
						else
						{
							return false;
						}
					}
					else
					{
						return true;
					}
				}
			}
			return false;
		}


		/**
		 * 从面板中移除一个道具
		 * @param prop
		 *
		 */
		public function removeProp(prop:ItemViewModel):void
		{
			var index:int=isContains(prop.name);

			if (index > -1)
			{
				var cell:CellGridBox=cellList[index]as CellGridBox;
				var temp:ItemViewModel=propList[index]as ItemViewModel;

				if (temp && cell)
				{
					cell.removeData();
					propList[index]=null;
					prop.removeEventListener(SelectionEvent.DRAG_PROP, draggingHandler);
					// prop.removeEventListener(PropEvent.STOPMOVE_PROP,moveStopHandler);
					prop.removeEventListener(MouseEvent.DOUBLE_CLICK, clickHandler);
				}
			}
		}

		/**
		 * 减少堆叠num个数量
		 * @param propName
		 *
		 */
		public function reduceStackCount(propName:String, num:int=1):Boolean
		{
			var index:int=isContains(propName);

			if (index > -1)
			{
				var cell:CellGridBox=cellList[index]as CellGridBox;
				var prop:ItemViewModel=propList[index]as ItemViewModel;

				if (cell && prop)
				{
					prop.dataModel.capability=prop.dataModel.currentCapability - num;
					cell.stackCount=cell.stackCount - num;
					return true;
				}
			}
			return false;
		}

		/**
		 * 清除使用过的道具
		 * @param pos
		 * @return
		 *
		 */
		public function removeUsingProp(pos:int):Boolean
		{
			var prop:ItemViewModel=null;

			//根据位置查找当前包裹中的所有道具
			for(var i:int=0; i < propList.length; i++)
			{
				var temp:ItemViewModel=propList[i]as ItemViewModel;

				if (temp)
				{

					//找到使用过需要删除的道具实例引用
					if (temp.dataModel.currentPosistion == pos)
					{
						prop=temp;
						break;
					}
				}
			}

			if (prop)
			{
				//得到所使用过道具的堆叠数量
				var count:int=prop.dataModel.currentCapability;

				//>1则减去一个,否则清除该道具
				if (count > 1)
				{
					var tag:Boolean=reduceStackCount(prop.name);
					MyLog.debug("reduce one prop in package..." + tag);

					if (tag)
					{
						prop.setUsing(false);
						return true;
					}
				}
				else
				{
					MyLog.debug("clear one prop in package..." + pos);
					removeProp(prop);
					return true;
				}
			}
			return false;
		}

		/**
		 * 打开道具的使用开关
		 * @param pos
		 * @return
		 *
		 */
		public function openUsingLimit(pos:int):Boolean
		{
			var prop:ItemViewModel=null;

			for(var i:int=0; i < propList.length; i++)
			{
				var temp:ItemViewModel=propList[i]as ItemViewModel;

				if (temp)
				{

					if (temp.dataModel.currentPosistion == pos)
					{
						prop=temp;
						break;
					}
				}
			}

			if (prop)
			{
				prop.setUsing(false);
				return true;
			}
			return false;
		}

		/**
		 * 根据道具在包裹中的ID判断该面板中是否包含该道具
		 * @param tag
		 * @return
		 *
		 */
		public function isContains(tag:String):int
		{

			if (propList && propList.length > 0)
			{
				var index:int=-1;

				for(var i:int=0; i < propList.length; i++)
				{
					var prop:ItemViewModel=propList[i];

					if (prop)
					{

						if (tag == prop.name)
						{
							index=i;
							break;
						}
					}
				}
			}
			return index;
		}

		public function getCellByPosition(pos:int):CellGridBox
		{
			var cell:CellGridBox=null;
			for(var i:int=0; i < totalCell; i++)
			{
				cell=cellList[i]as CellGridBox;
				if (cell.cellIndex == pos)
				{
					return cell;
				}
			}
			return null;
		}

		public function getItemByPosition(itemid:String, pos:int):ItemViewModel
		{
			var items:Array=getCurrentItems();
			var prop:ItemViewModel=null;

			//从每个包裹中查找当前包裹中的道具的最初绝对位置和pos相同且交易ID也相同的道具				
			if (items)
			{

				for(var j:int=0; j < items.length; j++)
				{
					var temp:ItemViewModel=items[j];
					if (pos == temp.dataModel.initPosition && itemid == temp.dataModel.id)
					{
						prop=temp;
						break;
					}
				}

				//当找到后就跳出循环
				if (prop)
				{
					return prop;
				}
			}
			return null;
		}

		/**
		 *  获得当前包裹中的所有道具
		 * @return
		 *
		 */
		public function getCurrentItems():Array
		{

			if (propList && propList.length > 0)
			{
				var temp:Array=new Array();

				for(var i:int=0; i < totalCell; i++)
				{

					if (propList[i])
					{
						temp.push(propList[i]);
					}
				}
				return temp;
			}
			return null;
		}

		public function getSaveItems():Array
		{

			if (propList && propList.length > 0)
			{
				var temp:Array=new Array();

				for(var i:int=0; i < totalCell; i++)
				{
					var prop:ItemViewModel=propList[i]as ItemViewModel;

					if (prop)
					{
						var nowIndex:int=prop.dataModel.currentPosistion + this.panelIndex * PackageHelper.AVERAGE_COUNT;

						if (prop.dataModel.initPosition != nowIndex)
						{
							temp.push(prop);
						}
					}
				}
				return temp;
			}
			return null;
		}

		/**
		 * 面板里面的道具是否拖动过
		 * @return
		 *
		 */
		public function hasDragged():Boolean
		{
			return isDrag;
		}

		/**
		 * 包裹是否已经满了
		 * @return
		 *
		 */
		public function isFull():Boolean
		{

			for(var i:int=0; i < cellList.length; i++)
			{
				var cell:CellGridBox=cellList[i];

				if (!cell.isFilled())
				{
					return false;
				}
			}
			return true;
		}

		/**
		 * 得到面板的宽和高
		 * @return
		 *
		 */
		public function get sizeWH():Point
		{
			return new Point(panelW, panelH);
		}

		public function get cellCount():int
		{
			return totalCell;
		}

		/**
		 * 得到所有单元容器
		 * @return
		 *
		 */
		public function getCells():Array
		{
			return cellList;
		}

		public function set packIndex(index:int):void
		{
			this.panelIndex=index;
		}

		public function get packIndex():int
		{
			return panelIndex;
		}

		public function refresh():void
		{
			var cell:CellGridBox=null;
			var prop:ItemViewModel=null;

			if (cellList)
			{

				for(var i:int=0; i < cellList.length; i++)
				{
					cell=cellList[i]as CellGridBox;
					cell.removeData();
				}
			}

			if (propList)
			{

				for(i=0; i < propList.length; i++)
				{
					prop=propList[i]as ItemViewModel;

					if (prop)
					{
						prop.removeEventListener(SelectionEvent.DRAG_PROP, draggingHandler);
						prop.removeEventListener(MouseEvent.DOUBLE_CLICK, clickHandler);
						prop.dispose();
						prop=null;
					}
				}
				propList[i]=null;
			}
			isDrag=false;
			oldTime=0;
		}

		/**
		 * 清除内存
		 *
		 */
		public function clearAll():void
		{
			var cell:CellGridBox=null;
			var prop:ItemViewModel=null;

			while(this.numChildren > 0)
			{
				this.removeChildAt(0);
			}

			if (cellList)
			{

				for(var i:int=0; i < cellList.length; i++)
				{
					cell=cellList[i]as CellGridBox;
					cell.clear();
				}
				cellList.splice(0);
				cellList=null;
			}

			if (propList)
			{

				for(i=0; i < propList.length; i++)
				{
					prop=propList[i]as ItemViewModel;

					if (prop)
					{
						prop.dispose();
					}
				}
				propList.splice(0);
				propList=null;
			}
			isDrag=false;
			oldTime=0;
		}
	}
}











